<?php
namespace Admin\Controller;
use Think\Controller;
class UserController extends Controller {
    //TP构造函数
    public function _initialize(){
        //自动加载的类
        new \Org\Admin_autoload();
        //当前页仅管理员以上可以访问
        /*if($this->admin_info['admin_group_id']>2){
            echo "<script>alert('当前页面仅管理员以上可以访问，请您使用管理员账号登录');history.back(-1);</script>";exit;
        }*/
    }
    //用户管理
    public function index(){
        $data['title']='用户管理 会员 - 找金银网';
        /*if(I('path.2')!=''){
            $page=I('path.2');
        }else{
            $page=1;
        }
        $perpage=10;
        $Model=D("Member");
        //搜索 关键词
        if(I('post.search')&&I('post.keyword')==''){
            session('user_keyword',null);
        }
        if(session('user_keyword')){
            $keyword=session('user_keyword');
        }
        if(I('post.search')&&I('post.keyword')){
            $keyword=I('post.keyword');
            session('user_keyword',I('post.keyword'));
        }
        //echo $keyword;exit;
        $Model->keyword=$keyword;

        //搜索 分类
        /*if(I('post.pc_id')){
            $Model->pc_id=I('post.pc_id');
        }*
        $Model->page=$page;
        $Model->perpage=$perpage;
        $user_list=$Model->get_user_list();
        //print_r($user_list);exit;
        $user_total=$Model->get_user_total();
        //echo $user_total;exit;
        $page_total=ceil($user_total/$perpage);
        //echo $page_total;exit;
        //分页数据
        if($page!=1&&$page_total>1){
            $last_page=$page-1;
        }else{
            $last_page=1;
        }
        if($page_total>$page){
            $next_page=$page+1;
        }else{
            $next_page=$page;
        }
        $pager['current_page']=$page;
        $pager['perpage']=$perpage;
        $pager['last_page']=$last_page;
        $pager['next_page']=$next_page;
        $pager['user_total']=$user_total;
        $pager['page_total']=$page_total;
        //$cat_list=$Model->get_cat_list();
        $this->assign("user_list", $user_list);
        //$this->assign("cat_list", $cat_list);
        $this->assign("pager",$pager);
        $this->assign("data", $data);*/
        $this->display();
    }
    //
    public function user_add(){
        $data['title']='添加用户 会员 - 找金银网';
        $this->assign("data", $data);
        $this->display();
    }
    //添加用户 提交
    public function user_add_post(){
        if($_POST['member_name']!=''&&$_POST['member_passwd']!=''){
            $post=I('post.');
            if(!empty($_FILES['member_avatar']['tmp_name'])){
                //上传图片
                $upload = new \Think\Upload();// 实例化上传类
                $upload->maxSize   =     3145728 ;// 设置附件上传大小
                $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
                $upload->rootPath  =     './data/upload/user/avatar/'; // 设置附件上传根目录
                $upload->savePath  =     ''; // 设置附件上传（子）目录
                $upload->subName='';
                $upload->saveName=md5(time());
                $info   =   $upload->upload();
                if(!$info) {// 上传失败
                    echo "<script>alert('上传失败，请您重新上传');history.back(-1);</script>";exit;
                }
                $member_avatar='/data/upload/user/avatar/'.$info['member_avatar']['savename'];
                $post['member_avatar']=$member_avatar;
            }
            $member_passwd=I('post.member_passwd');
            $post['member_passwd']=md5($member_passwd);
            $post['member_reg_time']=time();
            //print_r($post);exit;
            $Model=D("Member");
            $post['admin_id']=$this->admin_info['admin_id'];
            $post['admin_edit_time']=time();
            $Model->post=$post;
            if(!$Model->user_add_post()){
                echo "<script>alert('提交失败，请您尝试重新提交');history.back(-1);</script>";exit;
            }
            echo "<script>alert('提交成功');window.location.href='/user/user_add';</script>";
        }else{
            echo "<script>alert('请您填写完整后尝试重新提交');history.back(-1);</script>";exit;
        }
    }
    //查看用户
    public function user_view(){
        $data['title']='查看会员 - 找金银网';
        $member_id=I('path.2');
        $Model=D("Member");
        $Company=D("Company");
        $Model->member_id=$member_id;
        $Company->member_id=$member_id;
        $user_info=$Model->get_user_info();
        $company_info=$Company->get_company_info();
        //print_r($user_info);exit;
        $this->assign("data", $data);
        $this->assign("company_info",$company_info);
        $this->assign("user_info", $user_info);
        $this->display();
    }
    //编辑用户
    public function user_edit(){
        $data['title']='编辑用户 会员 - 找金银网';
        $member_id=I('path.2');
        $Model=D("Member");
        $Model->member_id=$member_id;
        $Company=D("Company");
        $Company->member_id=$member_id;
        $user_info=$Model->get_user_info();
        $company_info=$Company->get_company_info();
        //print_r($user_info);exit;
        $this->assign("data", $data);
        $this->assign("user_info", $user_info);
        $this->assign("company_info",$company_info);
        $this->display();
    }
    //更新用户信息
    public function user_edit_post(){
        $post=I('post.');
        if(!$post['member_truename']||!$post['member_telephone']||!$post['member_address']||!$post['company_name']||!$post['company_address']||!$post['company_tel']||!$post['company_part']||!$post['company_position']||!$post['product_purchase']||!$post['product_supply']||!$post['company_industry']||!$post['company_business']||!$post['company_scale']||!$post['company_range']){
            echo "<script>alert('填写不完整，请您填写完整后再提交');history.back(-1);</script>";exit;
        }
        //如果需要修改手机
        if(isset($_POST['member_mobile'])&&!$_POST['member_mobile']){
            echo "<script>alert('未填写手机号码，请您填写完整后再提交');history.back(-1);</script>";exit;
        }
        //如果需要修改邮箱
        if(isset($_POST['member_email'])&&!$_POST['member_email']){
            echo "<script>alert('未填写邮箱，请您填写完整后再提交');history.back(-1);</script>";exit;
        }
        //dump($_POST);exit;
        if($_POST['new_member_passwd']){
            $member_passwd=I('post.new_member_passwd');
            $post['member_passwd']=md5($member_passwd);
        }
        //如果未填写或者填了0，则转为NULL
        if((isset($_POST['member_mobile'])&&$_POST['member_mobile']=='')||(isset($_POST['member_mobile'])&&$_POST['member_mobile']==0)){
            $post['member_mobile']=NULL;
        }
        $Model=D("Member");
        $UC=M('Members','uc_','DB_CONFIG');
        //判断邮箱是否已经存在
        //先本地检测邮箱是否已被注册 如果本地没有，则UC检查，都没有，则可以修改
        $Model->post=$post;
        if($Model->check_email_exist()){
            echo "<script>alert('此邮箱已经被注册，如果是您的账号，请您登录，或者更换别的邮箱继续注册，谢谢');history.back(-1);</script>";exit;
        }
        //连接到UC端检测
        $where['email']=$post['member_email'];
        $count=$UC->where($where)->count();
        //echo $count;exit;
        if($count>0){
            echo "<script>alert('此邮箱已经被注册(本网站或关联网站)，请您尝试登录或使用别的邮箱进行注册，如有不明之处请联系客服人员');history.back(-1);</script>";exit;
        }
        //判断手机号码是否可以修改
        $Model->post=$post;
        if($Model->check_mobile_exist()){
            echo "<script>alert('此手机号码已经被注册，如果是您的账号，请您登录，或者更换别的手机号码继续注册，谢谢');history.back(-1);</script>";exit;
        }
        //连接到UC端检测
        $where['mobile']=$post['member_mobile'];
        $count=$UC->where($where)->count();
        //echo $count;exit;
        if($count>0){
            echo "<script>alert('此手机号码已经被注册(本网站或关联网站)，请您尝试登录或使用别的手机号码进行注册，如有不明之处请联系客服人员');history.back(-1);</script>";exit;
        }
        //判断完毕，修改本地数据库
        $post['admin_id']=$this->admin_info['admin_id'];
        $post['admin_edit_time']=time();
        if($post['member_passwd']){
            $post['member_passwd']=md5($post['member_passwd']);
        }
        //dump($post);exit;
        $Model->post=$post;
        if(!$Model->user_edit_post()){
            echo "<script>alert('更新用户信息失败，请您尝试重新提交');history.back(-1);</script>";exit;
        }
        $member_id=$post['member_id'];
        //同步修改到UC
        $UC=M('Members','uc_','DB_CONFIG');
        $uid=$member_id;
        //echo $uid;exit;
        if($post['member_email']){
            $data['email']=$post['member_email'];
        }
        if($post['member_mobile']){
            $data['mobile']=$post['member_mobile'];
        }
        if($post['member_passwd']){
            $data['password']=md5($post['member_passwd']);
        }
        if(is_array($data)){
            $result=$UC->where('uid='.$uid)->save($data);
            if($result === false) {
                echo "<script>alert('更新到UC失败');history.back(-1);</script>";
            }
        }
        //更新用户的公司信息
        $Model=D("Company");
        $Model->post=$post;
        if(!$Model->company_edit_post()){
            echo "<script>alert('提交失败，请您尝试重新提交');history.back(-1);</script>";exit;
        }
        echo "<script>alert('提交成功');window.location.href='/user/user_edit/$member_id';</script>"; //此处修改为跳转到列表
    }
    //更新排序及批量删除
    public function update_user()
    {
        if(I('post.ids')){
            $ids=I('post.ids');
            $Model=D("Member");
            $Model->ids=$ids;
            if(!$Model->delete_user()){
                echo "<script>alert('删除失败，请您尝试重新提交');history.back(-1);</script>";exit;
            }
            echo "<script>self.location=document.referrer;</script>";exit;
        }
        /*elseif(I('post.product_ids')){
            $ids=I('post.product_ids');
            $sorts=I('post.sorts');
            $Model=D("Product");
            $Model->ids=$ids;
            $Model->sorts=$sorts;
            if(!$Model->update_product_sort()){
                echo "<script>alert('更新失败，请您尝试重新提交');history.back(-1);</script>";exit;
            }
            echo "<script>self.location=document.referrer;</script>";
        }*/
    }

    //AJAX上传头像 单图
    public function ajax_upload_avatar(){
        $member_id=I('get.member_id');
        //echo $member_id;exit;
        //上传头像
        if(!empty($_FILES['avatar0']['tmp_name'])){
            $root_path=ROOT_PATH.'www/data/upload/user/avatar/'.$member_id;

            if(!is_dir($root_path)){
                mkdir($root_path);
            }
            //echo $root_path;exit;
            //上传图片
            $upload=new \Think\Upload();// 实例化上传类
            $upload->maxSize=2048000 ;// 设置附件上传大小
            $upload->exts=array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
            $upload->rootPath=$root_path.'/'; // 设置附件上传根目录
            $upload->savePath= ''; // 设置附件上传（子）目录
            $upload->subName='';
            $upload->saveName='avatar_'.md5(time());
            $info=$upload->upload();
            if(!$info) {// 上传失败
                echo "<script>alert('上传失败，请您重新上传');history.back(-1);</script>";exit;
            }
            $member_avatar='/data/upload/user/avatar/'.$member_id.'/'.$info['avatar0']['savename'];
            //$post['member_avatar']=$member_avatar;
            echo $member_avatar;exit;
        }

    }

    //ajax多图
    public function ajax_upload_image(){
        header('content-type:text/html charset:utf-8');
        $member_id=I('get.member_id');
        $dir_base = ROOT_PATH."www/data/upload/user/company/".$member_id; 	//文件上传根目录 此处为系统绝对路径
        $url_base =SELF_URL."/data/upload/user/company/".$member_id; //
        if(!is_dir($dir_base)){
            mkdir($dir_base);
        }
        //没有成功上传文件，报错并退出。
        if(empty($_FILES)) {
            echo "<textarea><img src='{$dir_base}error1.jpg'/></textarea>";
            exit(0);
        }
        $output = "<textarea>";
        $index = 0;		//$_FILES 以文件name为数组下标，不适用foreach($_FILES as $index=>$file)
        foreach($_FILES as $file){
            $upload_file_name = 'upload_file' . $index;		//对应index.html FomData中的文件命名
            $filename = $_FILES[$upload_file_name]['name'];
            $gb_filename = iconv('utf-8','gb2312',$filename);	//名字转换成gb2312处理
            //文件不存在才上传
            if(!file_exists($dir_base.$gb_filename)) {
                $isMoved = false;  //默认上传失败
                $MAXIMUM_FILESIZE = 2 * 1024 * 1024; 	//文件大小限制	1M = 1 * 1024 * 1024 B;
                $rEFileTypes = "/^\.(jpg|jpeg|gif|png){1}$/i";
                if ($_FILES[$upload_file_name]['size'] <= $MAXIMUM_FILESIZE &&
                    preg_match($rEFileTypes, strrchr($gb_filename, '.'))) {
                    $isMoved = @move_uploaded_file ( $_FILES[$upload_file_name]['tmp_name'], $dir_base.$gb_filename);		//上传文件
                }
            }else{
                $isMoved = true;	//已存在文件设置为上传成功
            }
            if($isMoved){
                //输出图片文件<img>标签
                //注：在一些系统src可能需要urlencode处理，发现图片无法显示，
                //    请尝试 urlencode($gb_filename) 或 urlencode($filename)，不行请查看HTML中显示的src并酌情解决。
                $output .= "<img src='{$url_base}{$filename}' title='{$filename}' alt='{$filename}'/>";
            }else {
                $output .= "<img src='{$dir_base}error3.jpg' title='{$filename}' alt='{$filename}'/>";
            }
            $index++;
        }
        echo $output."</textarea>";
        //echo "<textarea>".$url_base.$gb_filename."</textarea>";
    }
    //
    public function integral(){
        $data['title']='积分管理 会员 - 找金银网';
        $this->assign("data", $data);
        $this->display();
    }
    //
    public function prestore(){
        $data['title']='预存金额 会员 - 找金银网';
        $this->assign("data", $data);
        $this->display();
    }
    //
    public function binding(){
        $data['title']='分享绑定 会员 - 找金银网';
        $this->assign("data", $data);
        $this->display();
    }
    //
    public function label(){
        $data['title']='用户标签 会员 - 找金银网';
        $this->assign("data", $data);
        $this->display();
    }
}